<template>
  <view class="chat-container">
    <!-- 头部 -->
    <view class="chat-header">
      <view class="header-left">
        <uni-icons type="back" size="24" color="#333" @click="goBack"></uni-icons>
        <text class="header-title">AI运动指导</text>
      </view>
      <view class="header-right">
        <button class="end-btn" @click="showEndDialog" v-if="conversationId && !isConversationEnded">
          <uni-icons type="closeempty" size="14" color="#fff"></uni-icons>
          <text>结束</text>
        </button>
      </view>
    </view>

    <!-- 加载状态 -->
    <view class="loading-container" v-if="isLoading">
      <uni-icons type="spinner-cycle" size="32" color="#667eea"></uni-icons>
      <text class="loading-text">正在加载对话...</text>
    </view>

    <!-- 会话已结束提示 -->
    <view class="ended-notice" v-if="isConversationEnded">
      <uni-icons type="info" size="24" color="#f39c12"></uni-icons>
      <text class="ended-text">会话已结束，您可以返回重新开始新的对话</text>
    </view>

    <!-- 消息列表 -->
    <scroll-view 
      class="messages-container" 
      scroll-y 
      scroll-with-animation 
      :scroll-top="scrollTop"
      v-if="!isLoading"
    >
      <view class="messages-list">
        <view 
          v-for="(message, index) in messages" 
          :key="message.messageId || index"
          :class="['message-item', message.senderType === 'USER' ? 'user-message' : 'ai-message']"
        >
          <view class="message-avatar">
            <uni-icons 
              :type="message.senderType === 'USER' ? 'person-filled' : 'chatboxes-filled'" 
              size="20" 
              :color="message.senderType === 'USER' ? '#667eea' : '#27ae60'"
            ></uni-icons>
          </view>
          <view class="message-content">
            <text class="message-text">{{ message.content }}</text>
            <text class="message-time">{{ formatTime(message.timestamp) }}</text>
          </view>
        </view>

        <!-- AI正在输入提示 -->
        <view class="message-item ai-message" v-if="isAiTyping">
          <view class="message-avatar">
            <uni-icons type="chatboxes-filled" size="20" color="#27ae60"></uni-icons>
          </view>
          <view class="message-content typing-content">
            <view class="typing-indicator">
              <view class="dot"></view>
              <view class="dot"></view>
              <view class="dot"></view>
            </view>
            <text class="typing-hint">AI教练正在分析，请耐心等待...</text>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 推荐问题 -->
    <scroll-view 
      class="suggestions-container" 
      scroll-x 
      v-if="suggestedQuestions.length > 0 && !isConversationEnded"
    >
      <view class="suggestions-list">
        <view 
          v-for="(question, index) in suggestedQuestions" 
          :key="index"
          class="suggestion-item"
          @click="selectSuggestion(question)"
        >
          {{ question }}
        </view>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="input-container" v-if="!isConversationEnded">
      <view class="input-wrapper">
        <input 
          class="message-input" 
          v-model="currentMessage" 
          placeholder="请输入您想咨询的问题..."
          :disabled="isAiTyping || !conversationId"
          @confirm="sendMessage"
        />
        <button 
          class="send-btn" 
          :disabled="!currentMessage.trim() || isAiTyping || !conversationId"
          @click="sendMessage"
        >
          <uni-icons type="paperplane-filled" size="18" color="#fff"></uni-icons>
        </button>
      </view>
    </view>

    <!-- 结束会话确认弹窗已改为使用系统弹窗，见showEndDialog方法 -->
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { 
  createConversation, 
  askQuestion, 
  getConversation, 
  endConversation as apiEndConversation,
  getSuggestedQuestions 
} from '@/api/modules/AiGuidance.js'

// 获取页面参数
const pages = getCurrentPages()
const currentPage = pages[pages.length - 1]
const { resultId, userId, sportType = 'general' } = currentPage.options

// 状态管理
const isLoading = ref(true)
const conversationId = ref('')
const messages = ref([])
const currentMessage = ref('')
const isAiTyping = ref(false)
const isConversationEnded = ref(false)
const lastQuestionTime = ref(0) // 防重复发送
const suggestedQuestions = ref([])
const scrollTop = ref(0)
// const endDialog = ref(null) // 不再需要，已改用系统弹窗

// 初始化
onMounted(async () => {
  if (!resultId || !userId) {
    uni.showToast({
      title: '缺少必要参数',
      icon: 'none'
    })
    goBack()
    return
  }
  
  await initializeChat()
})

// 初始化聊天
const initializeChat = async () => {
  try {
    isLoading.value = true
    
    // 创建或获取已存在的会话
    const response = await createConversation({
      resultId,
      userId,
      sportType
    })
    
    if (response && response.conversationId) {
      conversationId.value = response.conversationId
      messages.value = response.messages || []
      
      // 检查会话状态
      isConversationEnded.value = response.status === 'COMPLETED'
      
      // 加载推荐问题
      if (!isConversationEnded.value) {
        await loadSuggestedQuestions()
      }
      
      // 滚动到底部
      scrollToBottom()
      
      console.log('会话初始化成功:', {
        conversationId: conversationId.value,
        messageCount: messages.value.length,
        status: response.status
      })
    } else {
      throw new Error('无法创建或获取会话')
    }
  } catch (error) {
    console.error('初始化聊天失败:', error)
    uni.showToast({
      title: '初始化失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
  }
}

// 发送消息
const sendMessage = async () => {
  const message = currentMessage.value.trim()
  if (!message || !conversationId.value || isAiTyping.value || isConversationEnded.value) {
    return
  }
  
  // 防重复发送：限制3秒内不能重复发送
  const now = Date.now()
  if (now - lastQuestionTime.value < 3000) {
    uni.showToast({
      title: '请稍后再试',
      icon: 'none'
    })
    return
  }
  lastQuestionTime.value = now
  
  // 添加用户消息
  const userMessage = {
    messageId: `user-${Date.now()}`,
    content: message,
    senderType: 'USER',
    timestamp: new Date().toISOString()
  }
  
  messages.value.push(userMessage)
  currentMessage.value = ''
  scrollToBottom()
  
  // 显示AI正在输入
  isAiTyping.value = true
  
  try {
    const response = await askQuestion({
      conversationId: conversationId.value,
      question: message,
      resultId,
      sportType
    })
    
    console.log('完整的response:', response)
    console.log('response类型:', typeof response)
    console.log('response.aiResponse:', response?.aiResponse)
    console.log('response.data:', response?.data)
    
    // 处理可能的嵌套数据结构
    const aiResponseData = response?.data?.aiResponse || response?.aiResponse
    
    if (response && aiResponseData) {
      // 添加AI回复
      const aiMessage = {
        messageId: response.messageId || `ai-${Date.now()}`,
        content: aiResponseData,
        senderType: 'AI_ASSISTANT',
        timestamp: response.timestamp || new Date().toISOString()
      }
      
      messages.value.push(aiMessage)
      
      // 更新推荐问题
      if (response.suggestedQuestions && Array.isArray(response.suggestedQuestions)) {
        suggestedQuestions.value = response.suggestedQuestions
      }
      
      scrollToBottom()
    } else {
      console.log('完整的response:', response)
      throw new Error('AI回复失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    
    // 特殊处理超时错误
    if (error.message && error.message.includes('超时')) {
      uni.showModal({
        title: '请求超时',
        content: 'AI正在思考中，处理时间较长。请稍后刷新页面查看回复，或点击确定重新加载对话。',
        confirmText: '重新加载',
        cancelText: '稍后查看',
        success: (res) => {
          if (res.confirm) {
            // 重新初始化对话
            setTimeout(() => {
              initializeChat()
            }, 1000)
          }
        }
      })
    } else {
      uni.showToast({
        title: '发送失败，请重试',
        icon: 'none'
      })
    }
  } finally {
    isAiTyping.value = false
  }
}

// 选择推荐问题
const selectSuggestion = (question) => {
  if (isConversationEnded.value) return
  
  currentMessage.value = question
  sendMessage()
}

// 加载推荐问题
const loadSuggestedQuestions = async () => {
  try {
    const response = await getSuggestedQuestions({
      resultId,
      sportType
    })
    
    if (response && Array.isArray(response)) {
      suggestedQuestions.value = response
    }
  } catch (error) {
    console.error('加载推荐问题失败:', error)
  }
}

// 显示结束会话确认 - 直接使用系统弹窗，更可靠
const showEndDialog = () => {
  uni.showModal({
    title: '确认结束会话',
    content: '结束会话后将无法继续当前对话，确定要结束吗？',
    confirmText: '确定',
    cancelText: '取消',
    confirmColor: '#e74c3c',
    success: (res) => {
      if (res.confirm) {
        endConversation()
      }
    }
  })
}

// 隐藏结束会话确认 - 系统弹窗自动关闭，无需手动处理
const hideEndDialog = () => {
  // 系统弹窗会自动关闭，这里不需要做任何操作
}

// 结束会话
const endConversation = async () => {
  if (!conversationId.value) return
  
  try {
    await apiEndConversation(conversationId.value)
    
    isConversationEnded.value = true
    suggestedQuestions.value = []
    
    // 添加系统消息
    const systemMessage = {
      messageId: `system-${Date.now()}`,
      content: '会话已结束。感谢您使用AI运动指导服务！',
      senderType: 'AI_ASSISTANT',
      timestamp: new Date().toISOString()
    }
    
    messages.value.push(systemMessage)
    scrollToBottom()
    
    uni.showToast({
      title: '会话已结束',
      icon: 'success'
    })
    
    // 系统弹窗会自动关闭，无需手动调用
  } catch (error) {
    console.error('结束会话失败:', error)
    uni.showToast({
      title: '结束会话失败',
      icon: 'none'
    })
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 滚动到底部
const scrollToBottom = () => {
  setTimeout(() => {
    scrollTop.value = 999999
  }, 100)
}

// 格式化时间
const formatTime = (timestamp) => {
  if (!timestamp) return ''
  
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (diff < 60000) return '刚刚'
  if (diff < 3600000) return `${Math.floor(diff / 60000)}分钟前`
  if (diff < 86400000) return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
  
  return date.toLocaleDateString('zh-CN', { month: '2-digit', day: '2-digit' }) + ' ' + 
         date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 清理
onUnmounted(() => {
  // 清理定时器等
})
</script>

<style>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

/* 头部样式 */
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: #fff;
  border-bottom: 1px solid #e5e5e5;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.end-btn {
  display: flex;
  align-items: center;
  gap: 3px;
  padding: 4px 8px;
  background-color: #e74c3c;
  color: white;
  border-radius: 12px;
  border: none;
  font-size: 12px;
  transition: all 0.2s;
}

.end-btn:active {
  transform: scale(0.95);
  background-color: #c0392b;
}

/* 加载状态 */
.loading-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 12px;
}

.loading-text {
  color: #667eea;
  font-size: 14px;
}

/* 会话结束提示 */
.ended-notice {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  background-color: #fff3cd;
  border-bottom: 1px solid #ffeaa7;
  margin-bottom: 1px;
}

.ended-text {
  color: #856404;
  font-size: 14px;
}

/* 消息列表 */
.messages-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.messages-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding-bottom: 20px;
}

.message-item {
  display: flex;
  gap: 8px;
  max-width: 85%;
}

.user-message {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.ai-message {
  align-self: flex-start;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 18px;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  flex-shrink: 0;
}

.message-content {
  background-color: #fff;
  padding: 12px 16px;
  border-radius: 16px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  position: relative;
}

.user-message .message-content {
  background-color: #667eea;
}

.message-text {
  font-size: 15px;
  line-height: 1.4;
  color: #333;
  word-wrap: break-word;
}

.user-message .message-text {
  color: #fff;
}

.message-time {
  display: block;
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.user-message .message-time {
  color: rgba(255,255,255,0.8);
}

/* 输入提示动画 */
.typing-indicator {
  display: flex;
  gap: 4px;
  margin-bottom: 4px;
}

.dot {
  width: 6px;
  height: 6px;
  border-radius: 3px;
  background-color: #999;
  animation: typing 1.4s infinite ease-in-out;
}

.dot:nth-child(1) { animation-delay: -0.32s; }
.dot:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
  0%, 80%, 100% { transform: scale(0.8); opacity: 0.5; }
  40% { transform: scale(1); opacity: 1; }
}

.typing-text {
  font-size: 13px;
  color: #999;
  font-style: italic;
}

.typing-hint {
  font-size: 12px;
  color: #27ae60;
  margin-top: 4px;
  display: block;
}

/* 推荐问题 */
.suggestions-container {
  padding: 12px 16px;
  background-color: #fff;
  border-top: 1px solid #e5e5e5;
  white-space: nowrap;
}

.suggestions-list {
  display: inline-flex;
  gap: 8px;
  padding: 4px 0;
}

.suggestion-item {
  padding: 8px 16px;
  background-color: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 20px;
  font-size: 14px;
  color: #495057;
  white-space: nowrap;
  transition: all 0.2s;
}

.suggestion-item:active {
  background-color: #667eea;
  color: #fff;
  transform: scale(0.98);
}

/* 输入区域 */
.input-container {
  padding: 12px 16px;
  background-color: #fff;
  border-top: 1px solid #e5e5e5;
}

.input-wrapper {
  display: flex;
  gap: 8px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
  min-height: 40px;
  max-height: 100px;
  padding: 10px 16px;
  border: 1px solid #e5e5e5;
  border-radius: 20px;
  background-color: #f8f9fa;
  font-size: 15px;
  line-height: 1.4;
}

.send-btn {
  width: 40px;
  height: 40px;
  border-radius: 20px;
  background-color: #667eea;
  border: none;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.2s;
}

.send-btn:disabled {
  background-color: #cccccc;
}

.send-btn:not(:disabled):active {
  transform: scale(0.95);
}
</style> 